﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using System.Text;
using Entity.Client;
using DAL;

public partial class facebookServicePage : System.Web.UI.Page
{
    //TODO: paste your facebook-app key here!!
    public const string FaceBookAppKey = "094a88e68625ff576df8e3b6c5cb44cf";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["action"] != null)
        {
            if (string.IsNullOrEmpty(Request.QueryString["access_token"])) return; //ERROR! No token returned from Facebook!!          
            string json = GetFacebookUserJSON(Request.QueryString["access_token"]);
            JavaScriptSerializer js = new JavaScriptSerializer();
            FacebookUser oUser = js.Deserialize<FacebookUser>(json);

            if (oUser != null)
            {
                //Response.Write("Welcome, " + oUser.name);
                //Response.Write("<br />id, " + oUser.id);
                //Response.Write("<br />email, " + oUser.email);
                //Response.Write("<br />first_name, " + oUser.first_name);
                //Response.Write("<br />last_name, " + oUser.last_name);
                //Response.Write("<br />gender, " + oUser.gender);
                //Response.Write("<br />link, " + oUser.link);
                //Response.Write("<br />updated_time, " + oUser.updated_time);
                //Response.Write("<br />birthday, " + oUser.birthday);
                //Response.Write("<br />locale, " + oUser.locale);
                //Response.Write("<br />picture, " + oUser.picture);
                //if (oUser.location != null)
                //{
                //    Response.Write("<br />locationid, " + oUser.location.id);
                //    Response.Write("<br />location_name, " + oUser.location.name);
                //}


                RegisterUsers objRegisterUsers = new RegisterUsers();
                RegUsers objRegUsers = new RegUsers();

                switch (Request.QueryString["action"].ToString())
                {
                    case "newUser":
                        objRegisterUsers.AuthType = 1;
                        objRegisterUsers.Country = 0;
                        objRegisterUsers.EmailAddress = oUser.email;
                        objRegisterUsers.FacebookID = oUser.id.ToString();
                        objRegisterUsers.Password = EncryptionMethods.Encryption.Encrypt("fbPassword");
                        objRegisterUsers.UserFullName = oUser.name;
                        objRegisterUsers.UserStatus = 1;
                        objRegisterUsers.UserBio = string.Empty;
                        objRegisterUsers.UserImageProfile = string.Empty;
                        int nReturnUserID = objRegUsers.InsertNewRegisterUser(objRegisterUsers);
                        if (nReturnUserID >= 1)
                        {
                            FormsFunction.SetCookieValue(nReturnUserID.ToString(), oUser.email);
                            Response.Redirect("~/Dashboard", false);
                        }
                        else
                        {
                            Response.Redirect("~/User?EID=1001", false);
                        }
                        break;
                    case "login":
                        objRegisterUsers.EmailAddress = oUser.email;
                        objRegisterUsers.Password = EncryptionMethods.Encryption.Encrypt("fbPassword");
                        int nUserID = objRegUsers.LoginClientUser(objRegisterUsers);
                        if (nUserID >= 1)
                        {
                            FormsFunction.SetCookieValue(nUserID.ToString(), objRegisterUsers.EmailAddress);
                            Response.Redirect("Dashboard", false);
                        }
                        else
                        {
                            Response.Redirect("~/User?EID=1002", false);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    /// <summary>
    /// sends http-request to Facebook and returns the response string
    /// </summary>
    private static string GetFacebookUserJSON(string access_token)
    {
        string url = string.Format("https://graph.facebook.com/me?access_token={0}&fields=email,name,first_name,last_name,link", access_token);

        WebClient wc = new WebClient();
        Stream data = wc.OpenRead(url);
        StreamReader reader = new StreamReader(data);
        string s = reader.ReadToEnd();
        data.Close();
        reader.Close();
        return s;
    }
}